import axios from 'axios'
import router from '../router'

// 创建自定义配置的 axios 实例
const request = axios.create({
  baseURL: '/api',  // 使用相对路径
  timeout: 15000,   // 增加超时时间
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
  }
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 修改配置方式
    Object.assign(config, {
      timeout: 15000,
      headers: {
        ...config.headers,
        'Content-Type': 'application/json',
      }
    })
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    const res = response.data
    console.log('Response:', res)
    
    if (res.code === 0) {
      return res
    } else if (res.code === 40100) {
      console.log('Not logged in')
      localStorage.clear()
      window.location.href = `${getCurrentDomain()}/login`
      return Promise.reject(new Error(res.message || '未登录'))
    } else if (res.code === 40300) {
      window.location.href = `${getCurrentDomain()}/call-limit?domain=${res.data?.domain || ''}&author=${res.data?.author || ''}`
      return Promise.reject(new Error(res.message || '调用次数已达上限'))
    } else {
      return Promise.reject(new Error(res.message || 'Error'))
    }
  },
  error => {
    console.error('Request error:', error)
    
    // 处理超时和网络错误的重试逻辑
    const config = error.config
    
    // 如果是超时错误，进行重试
    if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
      config.__retryCount = config.__retryCount || 0
      
      if (config.__retryCount < 3) {
        config.__retryCount++
        console.log(`Retrying request (${config.__retryCount}/3)`)
        
        // 重试时使用新的配置
        return new Promise(resolve => {
          setTimeout(() => {
            const newConfig = {
              ...config,
              timeout: 30000
            }
            resolve(request(newConfig))
          }, 1000)
        })
      }
    }

    if (error.response) {
      const { status, data } = error.response
      if (status === 401 || status === 40100) {
        localStorage.clear()
        window.location.href = `${getCurrentDomain()}/login`
      } else if (status === 403 || data.code === 40300) {
        window.location.href = `${getCurrentDomain()}/call-limit?domain=${data.data?.domain || ''}&author=${data.data?.author || ''}`
      }
      return Promise.reject(new Error(data?.message || '请求失败'))
    }
    return Promise.reject(error)
  }
)

export default request 